package com.volunteer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.volunteer.entity.User;
import com.volunteer.mapper.CommentMapper;
import com.volunteer.entity.Comment;
import com.volunteer.model.vo.CommentVO;
import com.volunteer.service.CommentService;
import com.volunteer.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 评论服务实现类
 */
@Service
@RequiredArgsConstructor
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    private final UserService userService;

    @Override
    public List<CommentVO> getComments(Long activityId) {
        // 查询活动下的所有评论
        List<Comment> comments = this.list(new LambdaQueryWrapper<Comment>()
                .eq(Comment::getActivityId, activityId)
                .orderByDesc(Comment::getCreateTime));

        if (comments.isEmpty()) {
            return new ArrayList<>();
        }

        // 获取所有评论的用户信息
        List<Long> userIds = comments.stream()
                .map(Comment::getUserId)
                .collect(Collectors.toList());
        List<User> users = userService.listByIds(userIds);
        Map<Long, User> userMap = users.stream()
                .collect(Collectors.toMap(User::getId, Function.identity()));

        // 转换为VO对象
        List<CommentVO> commentVOs = comments.stream()
                .map(comment -> {
                    CommentVO vo = new CommentVO();
                    BeanUtils.copyProperties(comment, vo);
                    User user = userMap.get(comment.getUserId());
                    if (user != null) {
                        vo.setUsername(user.getName());
                        vo.setUserAvatar(user.getAvatar());
                    }
                    return vo;
                })
                .collect(Collectors.toList());

        // 构建评论树
        Map<Long, CommentVO> commentMap = commentVOs.stream()
                .collect(Collectors.toMap(CommentVO::getId, Function.identity()));

        List<CommentVO> rootComments = new ArrayList<>();

        // 递归构建评论树
        for (CommentVO comment : commentVOs) {
            if (comment.getParentId() == 0) {
                rootComments.add(comment);
                buildCommentTree(comment, commentMap);
            }
        }

        return rootComments;
    }

    /**
     * 递归构建评论树
     * @param parent 父评论
     * @param commentMap 评论Map
     */
    private void buildCommentTree(CommentVO parent, Map<Long, CommentVO> commentMap) {
        // 查找所有子评论
        List<CommentVO> children = commentMap.values().stream()
                .filter(comment -> parent.getId().equals(comment.getParentId()))
                .collect(Collectors.toList());

        if (!children.isEmpty()) {
            if (parent.getChildren() == null) {
                parent.setChildren(new ArrayList<>());
            }
            parent.getChildren().addAll(children);

            // 递归处理子评论
            for (CommentVO child : children) {
                buildCommentTree(child, commentMap);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createComment(Long activityId, Long parentId, Long userId, String content) {
        Comment comment = new Comment();
        comment.setActivityId(activityId);
        comment.setParentId(parentId);
        comment.setUserId(userId);
        comment.setContent(content);
        comment.setLikes(0);
        return this.save(comment);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean likeComment(Long commentId, Long userId) {
        // 这里可以添加用户点赞记录表的操作
        return baseMapper.incrementLikes(commentId) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteComment(Long commentId, Long userId) {
        // 只能删除自己的评论
        return this.remove(new LambdaQueryWrapper<Comment>()
                .eq(Comment::getId, commentId)
                .eq(Comment::getUserId, userId));
    }
}
